package com.somsoft.handjc.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.somsoft.handjc.activity.MainActivity;
import com.somsoft.handjc.activity.setting.SetIpActivity;

/**
 * 为了保证程序能正常退出
 * 采用了网上介绍的方法
 * 每个Activity在onCreate的时候加入
 * MyApplication.getInstance().addActivity(this);
 * 
 * @author Administrator
 *
 */
public class BaseActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {			
		menu.add(Menu.NONE, 10, 10, "首页").setIcon(android.R.drawable.ic_menu_compass);
//		menu.add(Menu.NONE, 20, 20, "查询").setIcon(android.R.drawable.ic_menu_search);
//		menu.add(Menu.NONE, 50, 50, "设置IP").setIcon(android.R.drawable.ic_menu_set_as);
		menu.add(Menu.NONE, 90, 90, "退出").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		return true;											
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {		// 选中某个菜单项
		Intent it = null;
		switch (item.getItemId()) {								// 判断菜单项ID
		case  10:
			it = new Intent(BaseActivity.this,MainActivity.class);
			startActivity(it);
			break;
		case  50:
			it = new Intent(BaseActivity.this,SetIpActivity.class);
			startActivity(it);
			break;
		case  90:
			MyApplication.getInstance().exit();
			break;
		}
		return false;
	}
	
	/**
	 * 日期选择对话框验证
	 * @param start
	 * @param end
	 * @param dialog
	 * @param context
	 * @param cls
	 * @return
	 */
	protected boolean validateDate(String stDate,String edDate,DialogInterface dialog,Context context) throws Exception{
		try {
			setCloseable(dialog,false);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if("".equals(stDate)){
				Toast.makeText(context, "开始日期不能为空！", Toast.LENGTH_SHORT).show();
			}else if("".equals(edDate)){
				Toast.makeText(context, "结束日期不能为空！", Toast.LENGTH_SHORT).show();
			}else if(sdf.parse(edDate).getTime() <= sdf.parse(stDate).getTime()){
				Toast.makeText(context, "结束日期必须大于开始日期！", Toast.LENGTH_SHORT).show();
			}else{
				setCloseable(dialog,true);
				return true;
			}
		} catch (Exception e) {
			throw e;
		}
		return false;
	}
	
	protected void setCloseable(DialogInterface dialog,boolean flag) throws Exception{
		try {
			Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing"); 
	        field.setAccessible(true); 
	        field.set(dialog, flag); 
		} catch (Exception e) {
			throw e;
		}
	}
}
